package com.example.element.module.photo

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import android.media.ExifInterface
import android.net.Uri
import android.os.Build
import android.provider.MediaStore
import androidx.core.content.FileProvider
import com.example.common.base.AbsActivity
import com.example.element.R
import com.example.element.databinding.ActCameraAlbumBinding
import java.io.File

class CameraAlbumActivity : AbsActivity<ActCameraAlbumBinding>() {

    private val forAlbum = 2
    private val takePhoto = 1
    private lateinit var imageUri: Uri
    private lateinit var outputImage: File

    companion object {
        @JvmStatic
        fun open(context: Context) {
            context.startActivity(Intent(context, CameraAlbumActivity::class.java))
        }
    }

    override fun getLayoutId() = R.layout.act_camera_album

    override fun main() {
        //创建File,存储拍照后的照片
        outputImage = File(externalCacheDir, "output_image.jpg")
        if (outputImage.exists()) {
            outputImage.delete()
        }
        outputImage.createNewFile()
        //判断是否大于7.0,大于7.0 直接使用本地真实路径被认为不安全,抛异常。
        imageUri = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //7.0使用FileProvider,特殊的ContentProvider,将封装过的Uri共享给外部。（清单文件注册ContentProvider）
            FileProvider.getUriForFile(this, "com.example.element.photo", outputImage)
        } else {
            Uri.fromFile(outputImage)
        }
    }

    override fun initListener() {

        mBinding.btnCamera.setOnClickListener {
            //指定行为
            val intent = Intent("android.media.action.IMAGE_CAPTURE")
            //指定输出地址
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri)
            startActivityForResult(intent, takePhoto)
        }

        mBinding.btnAlbum.setOnClickListener {
            //打开文件选择器
            val intent = Intent(Intent.ACTION_OPEN_DOCUMENT)
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            //指定只显示图片
            intent.type = "image/*"
            startActivityForResult(intent, forAlbum)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            takePhoto -> {
                if (resultCode == Activity.RESULT_OK) {
                    //通过图片地址转化为bitmap
                    val bitmap = BitmapFactory.decodeStream(contentResolver.openInputStream(imageUri))
                    //设置图片，判断图片旋转情况
                    mBinding.ivPhoto.setImageBitmap(rotateIfRequired(bitmap))
                }
            }
            forAlbum -> {
                if (resultCode == Activity.RESULT_OK && data != null) {
                    //Intent的getData()方法来获取选中图片的Uri
                    data.data?.let {
                        val bitmap = getBitmapFromUri(it)
                        mBinding.ivPhoto.setImageBitmap(bitmap)
                    }
                }
            }
        }
    }

    /**
     * getBitmapFromUri()方法将Uri转换成Bitmap对象
     */
    private fun getBitmapFromUri(uri: Uri) = contentResolver.openFileDescriptor(uri, "r")?.use {
        BitmapFactory.decodeFileDescriptor(it.fileDescriptor)
    }


    /**
     * 判断图片旋转情况
     */
    private fun rotateIfRequired(bitmap: Bitmap): Bitmap {
        val exif = ExifInterface(outputImage.path)
        val orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL)
        return when (orientation) {
            ExifInterface.ORIENTATION_ROTATE_90 -> rotateIfRequired(bitmap, 90)
            ExifInterface.ORIENTATION_ROTATE_180 -> rotateIfRequired(bitmap, 180)
            ExifInterface.ORIENTATION_ROTATE_270 -> rotateIfRequired(bitmap, 270)
            else -> bitmap
        }
    }

    /**
     * 根据图片方向，旋转相应角度
     */
    private fun rotateIfRequired(bitmap: Bitmap, degree: Int): Bitmap {
        val matrix = Matrix()
        matrix.postRotate(degree.toFloat())
        val rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.width, bitmap.height, matrix, true)
        //将不需要的bitmap回收
        bitmap.recycle()
        return rotatedBitmap
    }
}